package leetcode.slidwidow;

import java.util.Objects;
import java.util.TreeMap;

public class Lc1438 {

    public int longestSubarray(int[] nums, int limit) {

        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        int l = 0, r = 0;
        int ans = 0;
        while (r < nums.length) {
            treeMap.put(nums[r], treeMap.getOrDefault(nums[r], 0) + 1);
            while (treeMap.lastKey() - treeMap.firstKey() > limit) {
                treeMap.put(nums[l], treeMap.get(nums[l]) - 1);
                if (treeMap.get(nums[l]) == 0)
                    treeMap.remove(nums[l]);
                l++;
            }
            ans = Math.max(ans, r - l + 1);
            r++;
        }
        return ans;
    }

    public static void main(String[] args) {
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        treeMap.put(1,2);
        System.out.println(treeMap.remove(2));

        Lc1438 lc1438 = new Lc1438();
        int[] a = {7,40,10,10,40,39,96,21,54,73,33,17,2,72,5,76,28,73,59,22,100,91,80,66,5,49,26,45,13,27,74,87,56,76,25,64,14,86,50,38,65,64,3,42,79,52,37,3,21,26,42,73,18,44,55,28,35,87};
        int l = 63;
        System.out.println(lc1438.longestSubarray(a, l));
    }
}
